from django.contrib import admin
from django.http import HttpResponse
import csv
import datetime
from django.utils.safestring import mark_safe
from django.urls import reverse
 
from . import models


def export_to_csv(modeladmin, request, queryset):

    """ Эта функция позволяет экспортировать данные модели в csv """

    options = modeladmin.model._meta
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename={}.csv'.format(options.verbose_name)
    writer = csv.writer(response)

    fields = [field for field in options.get_fields()
              if not field.many_to_many and not field.one_to_many]

    writer.writerow([field.verbose_name for field in fields])

    for obj in queryset:
        data_row = []

        for field in fields:
            value = getattr(obj, field.name)
            if isinstance(value, datetime.datetime): value = value.strftime('%d/%m/%Y')
            data_row.append(value)

        writer.writerow(data_row)

    return response



class OrderItemInline(admin.TabularInline):
    model = models.OrderItem
    raw_id_fields = ['product']


@admin.register(models.Order)
class OrderAdmin(admin.ModelAdmin):

    list_display = ['id', 'first_name', 'last_name', 'email', 'address',
                    'postal_code', 'city', 'paid', 'created', 'updated', 'order_pdf']
    list_filter = ['paid', 'created', 'updated']
    inlines = [OrderItemInline]
    actions = [export_to_csv]

    def order_pdf(self, object):

        return mark_safe('<a href="{}">PDF</a>' \
                .format(reverse('order:admin_order_pdf', args=[object.id])))

    order_pdf.short_description = 'Invoice'



export_to_csv.short_description = 'Export to CSV'
